<template>
    <div style='margin-bottom: 20px;'>
        <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState" @finish="onFinish">
            <a-row :gutter="24">
                <a-col :span="4">
                    <a-form-item name="username" label="管理员名称">
                        <a-input v-model:value="formState[`username`]" placeholder="请输入"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="4">
                    <a-form-item name="phone" label="管理员电话">
                        <a-input v-model:value="formState[`phone`]" placeholder="请输入"></a-input>
                    </a-form-item>
                </a-col>

                <a-col :span="4">
                    <a-form-item name="role" label="角色">
                        <a-radio-group v-model:value="formState['role']">
                            <a-radio-button value="">全部</a-radio-button>
                            <a-radio-button :value="1">普通管理员</a-radio-button>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :span="4">
                    <a-form-item name="status" label="状态">
                        <a-radio-group v-model:value="formState['status']">
                            <a-radio-button value="">全部</a-radio-button>
                            <a-radio-button :value="0">正常</a-radio-button>
                            <a-radio-button :value="1">冻结</a-radio-button>
                        </a-radio-group>
                    </a-form-item>
                </a-col>

            </a-row>
            <a-row>
                <a-col :span="20" style="text-align: left;margin-bottom: -50px;z-index: 100;">
                    <a-button type="primary" @click="adds" >新增</a-button>
                </a-col>
                <a-col :span="24" style="text-align: right">
                    <a-button type="primary" html-type="submit">查询</a-button>
                    <a-button style="margin: 0 8px" @click="() => { formRef.resetFields(); onFinish() }">重置</a-button>

                </a-col>
            </a-row>
        </a-form>
        <a-table bordered :data-source="dataSource" :columns="columns"
            :pagination="{ current, pageSize, total: totalCount }" @change="pageClick">

            <template #bodyCell="{ column, text, record }">

                <template v-if="column.dataIndex == 'role'">
                    <a-tag color="purple" v-if="record.role == 1">普通管理员</a-tag>
                </template>
                <template v-if="column.dataIndex == 'status'">
                    <span style="color:skyblue" v-if="record.status == 1">冻结</span>
                    <span style="color:green" v-if="record.status == 0">正常</span>
                    <span style="color:green" v-if="record.status == 2">注销</span>
                </template>


                <template v-if="column.dataIndex === 'operation'">
                    <a-popconfirm :title="'真的要删除吗'" @confirm="deleTraffic(record.uid)">
                        <a :style="{ color: share.color, marginLeft: '15px' }">删除</a>
                    </a-popconfirm>
                    <span :style="{ marginLeft: '15px', color: share.color }" @click="showModal(record)">修改</span>
                </template>
            </template>
        </a-table>
        <a-modal v-model:visible="addModel" title="交通新增" :width="850" @ok="addOk" :destroyOnClose="true">
            <a-form ref="addForm" :model="addFormState">
                <a-form-item label="用户名称" name="username" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model:value="addFormState.username" :maxlength="200" />
                </a-form-item>
                <a-form-item label="用户账号" name="account" :rules="[{ required: true, message: '请输入账号' }]">
                    <a-input v-model:value="addFormState.account" :maxlength="200" />
                </a-form-item>
                <a-form-item label="用户密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
                    <a-input v-model:value="addFormState.password" :maxlength="200" />
                </a-form-item>

                <a-form-item label="用户手机号" name="phone" :rules="[{ required: true, message: '请输入手机号' }]">
                    <a-input v-model:value="addFormState.phone" />
                </a-form-item>
                <a-form-item label="选择身份" name="role"
                    :rules="[{ required: true, message: '请选择身份!' }]">
                    <a-radio-group v-model:value="addFormState.role" name="role">
                        <a-radio value="1">普通管理员</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
            <div>
                <p>选择权限目录</p>
                <a-tree style="margin-left: 20px;"  v-model:checkedKeys="ADDcheckedKeys"
                    checkable :tree-data="share.treeData">
                </a-tree>
            </div>
        </a-modal>
        <!-- 修改操作 -->
        <a-modal v-model:visible="setModel" title="管理员修改" :width="850" @ok="setOk" :destroyOnClose="true">
            <a-form ref="setForm" :model="setFormState">
                <a-form-item label="用户名称" name="username" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model:value="setFormState.username" :maxlength="200" />
                </a-form-item>
                <a-form-item label="用户账号" name="account" :rules="[{ required: true, message: '请输入账号' }]">
                    <a-input v-model:value="setFormState.account" :maxlength="200" />
                </a-form-item>
                <a-form-item label="用户密码" name="password">
                    <a-input v-model:value="setFormState.password" :maxlength="200" />
                </a-form-item>

                <a-form-item label="用户手机号" name="phone" :rules="[{ required: true, message: '请输入手机号' }]">
                    <a-input v-model:value="setFormState.phone" />
                </a-form-item>
                <a-form-item label="选择身份" name="role"
                    :rules="[{ required: true, message: '请选择身份!' }]">
                    <a-radio-group v-model:value="setFormState.role" name="role">
                        <a-radio value="1">普通管理员</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="选择身份" name="status"
                    :rules="[{ required: true, message: '请选择身份!' }]">
                    <a-radio-group v-model:value="setFormState.status" name="role">
                        <a-radio value="0">正常</a-radio>
                        <a-radio value="1">冻结</a-radio>
                        <a-radio value="2">注销</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="冻结/注销原因" v-if="setFormState.status>0">
                    <a-textarea v-model:value="setFormState.reason" />
                </a-form-item>
            </a-form>
            <div>
                <p>选择权限目录</p>
                <a-tree style="margin-left: 20px;"  v-model:checkedKeys="SETcheckedKeys"
                    checkable :tree-data="share.treeData">
                </a-tree>
            </div>
        </a-modal>

    </div>
</template>

<script setup>

import { ref, onMounted, reactive,watch } from 'vue'
import { DownOutlined, UpOutlined, SwapRightOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { useUserData } from '../../../stores/userData';
import { useRouter } from 'vue-router';
import share from '../../../util/commnet'
import { message } from 'ant-design-vue';
import { MD5 } from "crypto-js";
import {setUserAPI} from '../../../api/setUser'
const store = useUserData();
const router = useRouter();
import {debounce} from 'lodash'


const formRef = ref('');    //搜索数据

const formState = reactive({  //搜素内容
    username: '',
    phone: "",
    status: '',
    role: '',

});

const dataSource = ref([{}]);   //表格数据
const totalCount = ref(0);      //总条
const pageSize = ref(10);       //一页多少条
const current = ref(1);         //当前页
const columns = [{
    title: '管理员名称',
    dataIndex: 'username',
    align: 'center'

}, {
    title: "电话",
    dataIndex: "phone",
    align: 'center',
    width: 100
}, {
    title: '注册时间',
    dataIndex: 'registration_time',
    align: 'center'

}, {
    title: "最后登录时间",
    dataIndex: 'last_login_time',
    align: 'center'

}, {
    title: '身份',
    dataIndex: 'role',
    align: 'center'

}, {
    title: "状态",
    dataIndex: "status",
    align: 'center'

}, {
    title: '操作',
    dataIndex: 'operation',
    align: 'center'

}];




const addForm = ref(null)
const addFormState = ref({});  //修改时表单的数据
const addModel = ref(false);
const ADDcheckedKeys = ref([]);

const adds = () => {
    addModel.value = true;
}



const addOk = ()=>{
    addForm.value.validateFields()
    .then(async res=>{
        if(ADDcheckedKeys.value.length<1){
            message.error("未选择权限！！");
            return
        }
        addFormState.value.file = share.filterArray(share.treeData,ADDcheckedKeys.value)
        console.log(addFormState);
        let add = await setUserAPI(`add|${addFormState.value.username}|${addFormState.value.phone}|${addFormState.value.account}|${MD5(addFormState.value.password).toString()}|${addFormState.value.role}|${JSON.stringify(addFormState.value.file)}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        if (!add || add.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (add.code != 200) {
            message.error(add.message);
            return
        }
        message.success(add.message);
        addModel.value = false;
        addFormState.value = {};
        pageClick()
        
    })
}


// 修改----------------------------------------------------------------------------------------------
const setForm  = ref(null)
const setFormState = ref({})
const setModel = ref(false)
const SETcheckedKeys = ref([]);
const showModal = async(item)=>{
    let res = await setUserAPI(`selDan|${item.uid}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {

        message.error(res.message);
        return
    }
    setFormState.value = res.data[0];
    setFormState.value.password = '';
    SETcheckedKeys.value = share.generateNewArray(share.treeData,res.file);
    setModel.value = true;
    console.log(SETcheckedKeys.value);
}
const setOk = async()=>{
    setForm.value.validateFields()
    .then(async res=>{
        const data = share.filterArray(share.treeData,SETcheckedKeys.value);
        let sets  = await setUserAPI(`set|${setFormState.value.uid}|${setFormState.value.username}|${setFormState.value.phone}|${setFormState.value.account}|${(setFormState.value.password).trim().length>0 ? MD5(setFormState.value.password).toString():''}|${setFormState.value.role}|${setFormState.value.status}|${setFormState.value.reason}|${JSON.stringify(data)}|${setFormState.value.role_dir}|${store.data.token}|${store.data.uuid}|${store.data.phone}`)
        console.log(sets);
        if (!sets || sets.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (sets.code != 200) {

            message.error(sets.message);
            return
        }
        message.success('修改成功');
        setModel.value = false;
        setFormState.value = {};

        pageClick()
    })
}

//删除------------------------------------------------------------------


const deleTraffic = async(uid)=>{
    let res =await setUserAPI(`del|${uid}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {

        message.error(res.message);
        return
    }
    message.success("删除成功");
    pageClick();
}
const onFinish = () => {  //条件查询
    pageClick();
}



const debouncedPageClick = debounce(async (item) => {           //进行防抖
    item ? current.value = item.current : current.value = 1;
    let res = await setUserAPI(`sel|${formState.username}|${formState.phone}|${formState.role}|${formState.status}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {

        message.error(res.message);
        return
    }
    dataSource.value = res.data
    totalCount.value = res.total - 0;
    console.log(res);
}, 300);

const pageClick = (item) => {       //页面变化刷新表格
    debouncedPageClick(item);
};







onMounted(async () => {
    let res = await setUserAPI(`sel|${formState.username}|${formState.phone}|${formState.role}|${formState.status}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message);
        return
    }
    dataSource.value = res.data;
    totalCount.value = res.total - 0;
    
})

</script>